package com.ware.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;

import com.baidu.ueditor.ActionEnter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.ware.jfinal.plugin.shiro.SH;
import com.ware.util.AjaxResult;
import com.ware.util.ImageUtil;
import com.ware.util.UploadUtil;

public class BaseController extends Controller{

	/**
	 * @param opType 1品种管理，2厂商管理，3单位管理，4出库，5入库,6品类
	 * @param content 操作内容
	 */
//	public void addLog(int opType, String content) {
//		Log.dao.clear().set("op_type", opType).set("op_content", content)
//			.set("op_time", new Date())
//			.save();
//			
//	}
	
	private static final int MAX_IMG_SIZE = 5242880;
	private static final Map<String, Integer[]> IMG_SIZE = new HashMap<String, Integer[]>();
	
	public BaseController() {
		IMG_SIZE.put("brand", new Integer[]{640, 360});
		IMG_SIZE.put("menu", new Integer[]{640, 427});
		IMG_SIZE.put("store", new Integer[]{640, 360});
	}
	
	public void renderAjaxOk(){
		AjaxResult result = new AjaxResult(1);
		this.renderJson(result.toJson());
	}
	
	public void renderAjaxError(String msg){
		AjaxResult result = new AjaxResult(0);
		result.setInfo(msg);
		this.renderJson(result.toJson());
	}

	public Map<String, String> fromJson(String value) throws Exception {
		Gson gson = new Gson();
		
		return gson.fromJson(value, new TypeToken<Map<String, String>>(){}.getType());
	}
	
	/******************  获取请求参数 *****************************/
	public Map<String, Object> getParamMap(){
		Map<String, Object> record = new HashMap<String, Object>();
		Map<String, String[]> map= this.getParaMap();
		Set<String> keys = map.keySet();
		for (String string : keys) {
			//if(map.get(string)[0] != null && !"".equals(map.get(string)[0])){
				record.put(string, map.get(string)[0]);
			//}
		}
		return record;
	}
	/**
	 * 保存客户端上传的图片文件 
	 * @param field  客户端表单的file字段名
	  * @return 相对于当前用户根目录的图片路径.
	 */
	protected String saveImageFile(String field){
		return saveImageFile(field,SH.getUser().getUserId(),"");
	}
	
	/**
	 * 保存客户端上传的图片文件 
	 * @param field  客户端表单的file字段名
	 * @param userId 当前用户的id	
	 * @return 相对于当前用户根目录的图片路径.
	 */
	protected String saveImageFile(String field,int userId){
		return saveImageFile(field,userId,"");
	}
	
	/**
	 * 保存客户端上传的图片文件 
	 * @param field  客户端表单的file字段名
	 * @param userId 当前用户的id	
	 * @param destFilePath  目标文件路径
	 * @return 相对于当前用户根目录的图片路径.
	 */
	protected String saveImageFile(String field, int userId, String destFilePath){
		return saveImageFile(field, userId, destFilePath, "");
	}
	
	/**
	 * 保存客户端上传的图片文件 
	 * @param field  客户端表单的file字段名
	 * @param userId 当前用户的id	
	 * @param destFilePath  目标文件路径
	 * @param fileName 指定图片名称
	 * @return 相对于当前用户根目录的图片路径.
	 */
	protected String saveImageFile(String field, int userId, String destFilePath, String fileName){
		String tempPath = UploadUtil.getTempPath(userId,destFilePath);
		File file = this.getFile(field, tempPath,MAX_IMG_SIZE).getFile();
		
		//检测文件是否合法
		if(!UploadUtil.checkImg(file.getName())){
			file.delete();
			throw new RuntimeException("图片文件格式不合法，只接受【jpg|gif|bmp|png|jpeg】格式的图片");
		}
		
		//重新命名
		if (!fileName.equals("")) {
			fileName = fileName + UploadUtil.getFileExt(file.getName());
			
			File temp = new File(tempPath + fileName);
			if (temp.exists()) temp.delete();
			
			file.renameTo(temp);
			
			file = temp;
		}
		
		String randFileName = fileName.equals("") ? UploadUtil.randFileName(file.getName()) : fileName;
		
		String key=this.getPara("key","");
		String value="";
		
		if(!key.equals("") && !(value=ImageUtil.getValue(key)).equals("")){
			String baseSrc="";
			String baseStore="";
			
			File imageFile=new File(tempPath+file.getName());
			
			String [] list=value.split(",");

			for (int i = 0; i < list.length; i++) {
				String[] values=list[i].split(":");
				
				if(!Pattern.compile("[a-z]{1,10}:[0-9]{1,10}\\*[0-9]{1,10}").matcher(list[i]).matches())
					throw new RuntimeException("配置文件格式不正确!");
				
				String basePath=UploadUtil.getSavePath(userId,destFilePath,values[0]);
				File baseFile=new File(basePath);
				if(!baseFile.exists()) baseFile.mkdirs();
				
				baseSrc=basePath+file.getName();
				String storeDir = UploadUtil.getStoreFilePath(userId, destFilePath,values[0]);
				baseStore = storeDir + randFileName;
				
				String[] paramets=values[1].split("\\*");
		        int width=Integer.parseInt(paramets[0]); //图片宽度
		        int height=Integer.parseInt(paramets[1]); //图片高度
		        
		        if(UploadUtil.isSae()){
		        	try{
		        		UploadUtil.resizeImageToStore(imageFile, baseStore, width, height);
					}catch(Exception e){		
						throw new RuntimeException("保存文件到OSS失败:"+e.getMessage());
					}		        	
		        }else{
		        	ImageUtil.resize(imageFile, baseSrc,width,height);
		        }				
			}
		}
		
		//如果不是sae环境，直接返回文件名.
		if(!UploadUtil.isSae()){
			return UploadUtil.formatPath(destFilePath) + file.getName();
		}

		//获取临时文件路径
		String srcFileName = tempPath + file.getName();
		//生成storage目标文件路径
		String storeDir = UploadUtil.getStoreFilePath(userId, destFilePath);
		String storeFileName = storeDir + randFileName;
		
		//将文件上传到storage中
		try{
			UploadUtil.uploadImageToStore(srcFileName, storeFileName);
		}catch(Exception e){		
			throw new RuntimeException("保存文件到OSS失败:"+e.getMessage());
		}finally{ 
			file.delete();
		}
		return UploadUtil.formatPath(destFilePath) + randFileName;		
	}	
	
	/**
	 * 保存网络图片
	 * @param userId 当前用户
	 * @param imgUrl 图片的连接地址
	 * @return 相对于当前用户根目录的图片路径.
	 */
	public String saveWebImgFile(int userId, String imgUrl) {
		return this.saveWebImgFile(userId, imgUrl, "");
	}
	
	/**
	 *保存网络图片
	 *@param userId 当前用户的id
	 *@param imgUrl 图片的连接地址 
	 *@param destFilePath 目标路径
	 *@return 相对于当前用户根目录的图片路径.
	 */
	public String saveWebImgFile(int userId, String imgUrl, String destFilePath) {
		return this.saveWebImgFile(userId, imgUrl, destFilePath, "");
	}
	
	/**
	 *保存网络图片
	 *@param userId 当前用户的id
	 *@param imgUrl 图片的连接地址 
	 *@param destFilePath 目标路径
	 *@param fileName 指定文件名称
	 *@return 相对于当前用户根目录的图片路径.
	 */
	public String saveWebImgFile(int userId, String imgUrl, String destFilePath, String fileName) {
		String tempPath = UploadUtil.getTempPath(userId,destFilePath);
		String imgName = UploadUtil.parseFileName(imgUrl);
		
		if (!UploadUtil.checkImg(imgName)) {
			throw new RuntimeException("图片文件格式不合法，只接受【jpg|gif|bmp|png|jpeg】格式的图片");
		}
		
		if (!fileName.equals("")) {
			fileName = fileName + UploadUtil.getFileExt(imgName);
			UploadUtil.deleteExist(tempPath + fileName);
		}
		
		try {
			if (imgUrl.startsWith("https://"))
				imgUrl = "http://" + imgUrl.substring(8); 
				new URL(imgUrl);
		} catch (Exception e) {
			throw new RuntimeException("请填写正确的图片URL");
		}
		
		String randFileName = fileName.equals("") ? UploadUtil.randFileName(imgName) : fileName;
		String srcFileName = tempPath + randFileName;
		
		File file = new File(tempPath);
		if (!file.exists()) {
			file.mkdirs();
		}
		file = new File(srcFileName);
		
		try {
			GetMethod getMethod = new GetMethod(imgUrl);
			
			new HttpClient().executeMethod(getMethod);
			
			InputStream in = getMethod.getResponseBodyAsStream();
			
			
			FileOutputStream fos = new FileOutputStream(file);
			
	        byte[] buf = new byte[1024];  
	        int len = 0;  
	        while ((len = in.read(buf)) != -1) {  
	            fos.write(buf, 0, len);  
	        }  
	        fos.flush();  
	        fos.close();
	        
		} catch (Exception e) {
			throw new RuntimeException("获取图片失败:"+e.getMessage());
		} 
		
		String key=this.getPara("key","");
		String value="";
		
		if(!key.equals("") && !(value=ImageUtil.getValue(key)).equals("")){
			String baseSrc="";
			String baseStore="";
			
			String [] list=value.split(",");

			for (int i = 0; i < list.length; i++) {
				String[] values=list[i].split(":");
				
				if(!Pattern.compile("[a-z]{1,10}:[0-9]{1,10}\\*[0-9]{1,10}").matcher(list[i]).matches())
					throw new RuntimeException("配置文件格式不正确!");
				
				String basePath=UploadUtil.getSavePath(userId,destFilePath,values[0]);
				File baseFile=new File(basePath);
				if(!baseFile.exists()) baseFile.mkdirs();
				
				baseSrc=basePath+file.getName();
				String storeDir = UploadUtil.getStoreFilePath(userId, destFilePath,values[0]);
				baseStore = storeDir + randFileName;
				
				String[] paramets=values[1].split("\\*");
		        int width=Integer.parseInt(paramets[0]); //图片宽度
		        int height=Integer.parseInt(paramets[1]); //图片高度
		        
		        if(UploadUtil.isSae()){
		        	try{
		        		UploadUtil.resizeImageToStore(file, baseStore, width, height);
					}catch(Exception e){		
						throw new RuntimeException("保存文件到OSS失败:"+e.getMessage());
					}		        	
		        }else{
		        	ImageUtil.resize(file, baseSrc,width,height);
		        }				
			}
		}
		
		 //如果不是sae环境，直接返回文件名.
		if(!UploadUtil.isSae()){
			return UploadUtil.formatPath(destFilePath) + file.getName();
		}
		
		randFileName = UploadUtil.randFileName(randFileName);
		try {
			//生成storage目标文件路径
    		String storeDir = UploadUtil.getStoreFilePath(userId, destFilePath);
    		String storeFileName = storeDir +randFileName;
    		UploadUtil.uploadImageToStore(srcFileName, storeFileName);
		} catch (Exception e) {
			throw new RuntimeException("保存文件到storage失败:"+e.getMessage());
		}finally {
			file.delete();
		}
		
		return UploadUtil.formatPath(destFilePath) + randFileName;
	}
	
	public String saveImageFile(File file, int userId, String destFilePath) throws Exception{
		String tempPath = UploadUtil.getTempPath(userId,destFilePath);
		
		//检测文件是否合法
		if(!UploadUtil.checkImg(file.getName())){
			file.delete();
			throw new RuntimeException("图片文件格式不合法，只接受【jpg|gif|bmp|png|jpeg】格式的图片");
		}
		
        if(!UploadUtil.isSae()){
        	return UploadUtil.formatPath(destFilePath) + file.getName();
		}
        
        //获取临时文件路径
		String srcFileName = tempPath + file.getName();
		//生成storage目标文件路径
		//String randFileName = fileName.equals("") ? UploadUtil.randFileName(file.getName()) : fileName;
		String storeDir = UploadUtil.getStoreFilePath(userId, destFilePath);
		String storeFileName = storeDir + file.getName();
		
		//将文件上传到storage中
		try{
			return UploadUtil.uploadImageToStore(srcFileName, storeFileName);
		}catch(Exception e){		
			throw new RuntimeException("保存文件到storage失败:"+e.getMessage());
		}finally{ 
			file.delete();
		}
		
	}
	
	public void uEditorImg() {		
//		if (this.getPara("noCache") != null) {
			this.getResponse().setHeader("Content-Type" , "text/html");
			
			String rootPath = JFinal.me().getServletContext().getRealPath("/");//application.getRealPath( "/" );
			String ss = new ActionEnter( this.getRequest(), rootPath ).exec();
			System.out.println(ss);
			this.renderJson(ss);
			return;
//		}
//		int userId = SH.getUser().getUserId();		
//		String fileName = "";
//		try{
//			String tempPath = UploadUtil.getTempPath(userId, "eEditor");
//			
//			File file = this.getFile("upfile", tempPath,300*1024).getFile();
//			
//			fileName = this.saveImageFile("upfile", userId, "eEditor");	
//			
//			if (file.exists()) {
//				file.delete();
//			}
//		}catch(Exception e){
//			e.printStackTrace();
//			this.renderJson("{'state' : '上传图片失败:" + e.getMessage() + "'}");
//			return;
//		}			
//		String title = this.getPara("pictitle","");
//		String originalName = this.getPara("fileName","");
//		String url = UploadUtil.getWxImageUrl(userId, fileName);
//		
//		this.renderJson("{'original':'"+originalName+"','url':'"+ url +"','title':'"+title+"','state':'SUCCESS'}");
	}
	
	public void uploadImg() throws Exception{		
		AjaxResult result = new AjaxResult(1);		
		try {
			int userId = SH.getUser().getUserId();
			String mobile = this.getPara("mobile", "");
			String path = this.getPara("path", "");
				
			String fileName = mobile.equals("") ? this.saveImageFile("local_img", userId)
								: this.saveImageFile("local_img", userId, path, mobile);
			
			String fileUrl = UploadUtil.getImageUrl(userId,fileName);
			
			result.setData("fileName", fileName);
			result.setData("fileUrl", fileUrl);			
		} catch (Exception e) {
			e.printStackTrace();
			result.addError("上传图片失败:"+e.getMessage());
		}	
		
		this.renderJson(result.toJson());
	}
	
	public void uploadWebImg() {
		AjaxResult result = new AjaxResult(1);
		
		try {
			String imgUrl = this.getPara("web_img", "");
			
			String mobile = this.getPara("mobile", "");
			String path = this.getPara("path", "");
			
			int userId = SH.getUser().getUserId();
			
			String fileName = mobile.equals("") ? this.saveWebImgFile(userId, imgUrl) 
										: this.saveWebImgFile(userId, imgUrl, path, mobile);
			
			String fileUrl = UploadUtil.getImageUrl(userId,fileName);
			
			result.setData("fileName", fileName);
			result.setData("fileUrl", fileUrl);
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatus(0);
			result.setInfo("上传图片失败:"+e.getMessage());
		}
		
		this.renderJson(result.toJson());
	}
	
	
}
